# -*- coding: utf-8 -*-

"""
@Datetime: 2019/2/15
@Author: Zhang Yafei
"""
import requests
from application import app
import hashlib, base64, random, string


class MemberService(object):
    @staticmethod
    def genAuthCode(memberinfo):
        m = hashlib.md5()
        str = '{}-{}-{}'.format(memberinfo.id, memberinfo.salt, memberinfo.status)
        m.update(str.encode('utf-8'))
        return m.hexdigest()

    @staticmethod
    def geneSalt(length=16):
        key_list = [random.choice((string.ascii_letters + string.digits)) for _ in range(length)]
        return (''.join(key_list))

    @staticmethod
    def getWechatOpenid(code):
        url = 'https://api.weixin.qq.com/sns/jscode2session?appid={0}&secret={1}&js_code={2}&grant_type=authorization_code' \
            .format(app.config['MINA_APP']['appid'], app.config['MINA_APP']['appkey'], code)
        content = requests.get(url)
        response = content.json()
        openid = None
        if 'openid' in response:
            openid = response['openid']
        return openid